package com.example.pkmedical.Activity.usermsg;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.pkmedical.Activity.model.UserMessage;
import com.example.pkmedical.Base.BaseActivity;
import com.example.pkmedical.Event.MessageWrap;
import com.example.pkmedical.R;
import com.example.pkmedical.Utils.CommandUtil;
import com.example.pkmedical.Utils.EventBusUtils;
import com.example.pkmedical.Utils.NumberUtil;
import com.example.pkmedical.Utils.SPUtils;
import com.example.pkmedical.Utils.SerialProtUtil;
import com.example.pkmedical.Utils.ToastUtils;
import com.google.gson.Gson;

import org.litepal.LitePal;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NewPatientNextActivity extends BaseActivity {

    @BindView(R.id.main_house)
    ImageView mainHouse;
    @BindView(R.id.main_house_text)
    TextView mainHouseText;
    @BindView(R.id.main_date)
    TextView mainDate;
    @BindView(R.id.user_ok_bt)
    Button userOkBt;
    @BindView(R.id.user_ok_cancle)
    Button userOkCancle;
    @BindView(R.id.user_sex_layout)
    RelativeLayout userSexLayout;
    @BindView(R.id.user_sex_edit)
    EditText userSexEdit;
    @BindView(R.id.user_date_edit)
    EditText userDateEdit;
    @BindView(R.id.user_name_edit)
    EditText userNameEdit;
    @BindView(R.id.user_age_edit)
    EditText userAgeEdit;
    @BindView(R.id.user_height_edit)
    EditText userHeightEdit;
    @BindView(R.id.user_weight_edit)
    EditText userWeightEdit;
    private PopupWindow SexPop;
    private boolean mSex = true;
    TimePickerView pvTime;
    private boolean isNull = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_user_next);
        ButterKnife.bind(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        LitePal.getDatabase();
    }

    @Override
    public void initData() {

        setCanNotEditAndClick(userSexEdit);
        setCanNotEditAndClickDate(userDateEdit);
    }

    public void setCanNotEditAndClick(View view) {
        userSexEdit.setFocusable(false);
        userSexEdit.setFocusableInTouchMode(false);
        userSexEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initCefanWindow();
            }
        });
    }

    public void setCanNotEditAndClickDate(View view) {
        userDateEdit.setFocusable(false);
        userDateEdit.setFocusableInTouchMode(false);
        userDateEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DateSelector();
            }
        });
    }

    @Override
    public void initView() {
        mainHouse.setImageResource(R.drawable.img_title_usermsg);
        mainHouseText.setText(R.string.title_user);
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void showDialog(String... msg) {

    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @OnClick({R.id.user_ok_bt, R.id.user_ok_cancle})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.user_ok_bt:
//                LitePal.deleteDatabase("newdb");
                saveData();
                doDefult();


                if (isNull) {

                } else {
                    List<UserMessage> area = LitePal.findAll(UserMessage.class);
                    Log.d("yangshuo", new Gson().toJson(area));
                    EventBusUtils.post(MessageWrap.getInstance(MessageWrap.USER_MESSAGE, 1));
                    NewPatientNextActivity.this.finish();
                }

                break;
            case R.id.user_ok_cancle:
                finish();
                break;

        }
    }

    private void doDefult() {
        SerialProtUtil.getInstance().sendBytes(2, CommandUtil.CHANGGUI_TTYPE);
        EventBusUtils.post(MessageWrap.getInstance(MessageWrap.USER_MESSAGE_TIME, 1));
        CommandUtil.LEAVEBED_TYPE = 0;
        CommandUtil.HEAD_WARNING_TYPE = 0;
//        SPUtils.getInstance().put("bed_final_angle", 0);
        SPUtils.getInstance().put("user_height", "不适用");
        SPUtils.getInstance().put("user_first_weight", getString(R.string.weight_device_no_apply));
        SPUtils.getInstance().put("user_last_weight", getString(R.string.weight_device_no_apply));
        SPUtils.getInstance().put("user_now_weight", getString(R.string.weight_device_no_apply));
        SPUtils.getInstance().put("user_difference_weight_all", "0");
        SPUtils.getInstance().put("comfortable_FootNum", CommandUtil.CHANGGUI_HEAD);
        SPUtils.getInstance().put("comfortable_HipNum", CommandUtil.CHANGGUI_HIP);
        SPUtils.getInstance().put("comfortable_HeadNum", CommandUtil.CHANGGUI_FOOT);
        SPUtils.getInstance().put("rollover_left_minute", CommandUtil.ROLLOVER_LEFT_TIME);
        SPUtils.getInstance().put("rollover_ping_minute", CommandUtil.ROLLOVER_PING_TIME);
        SPUtils.getInstance().put("rollover_right_minute", CommandUtil.ROLLOVER_RIGHT_TIME);
        SPUtils.getInstance().put("rollover_left_bfb", CommandUtil.ROLLOVER_LEFT_NUM);
        SPUtils.getInstance().put("rollover_right_bfb", CommandUtil.ROLLOVER_RIGHT_NUM);
        SPUtils.getInstance().put("shock_qiangdu_qiaoji", CommandUtil.SHOCK_QIAOJI_STRENGTH);
        SPUtils.getInstance().put("shock_qiangdu_zhendong", CommandUtil.SHOCK_ZHENDONG_STRENGTH);
        SPUtils.getInstance().put("shock_time_qiaoji", CommandUtil.SHOCK_QIAOJI_TIME);
        SPUtils.getInstance().put("shock_time_zhendong", CommandUtil.SHOCK_ZHENDONG_TIME);
        SPUtils.getInstance().put("TOZERO_DATA", CommandUtil.TOZERO_DEFAULT_TIME);
        SPUtils.getInstance().put("NEWUSER_ZERO_DATA", CommandUtil.TOZERO_DEFAULT_TIME);
        SPUtils.getInstance().put("Initial_time", CommandUtil.TOZERO_DEFAULT_TIME);
        SPUtils.getInstance().put("Last_time", CommandUtil.TOZERO_DEFAULT_TIME);
        CommandUtil.IS_FIRST = true;
    }

    /**
     * 选择器
     */
    private void initCefanWindow() {
        View view = LayoutInflater.from(this).inflate(R.layout.item_sex_layout, null);
        RelativeLayout tv_man = view.findViewById(R.id.rollover_item_man);
        RelativeLayout tv_woman = view.findViewById(R.id.rollover_item_woman);
        if (!mSex) {
            tv_woman.setVisibility(View.GONE);
        } else {
            tv_man.setVisibility(View.GONE);
        }

        tv_man.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                userSexEdit.setText(R.string.man);
                mSex = true;
                SexPop.dismiss();
            }
        });
        tv_woman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                userSexEdit.setText(R.string.woman);
                mSex = false;
                SexPop.dismiss();
            }
        });
        SexPop = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        SexPop.setFocusable(true);
        SexPop.setOutsideTouchable(true);
        SexPop.setBackgroundDrawable(new ColorDrawable());
        SexPop.showAsDropDown(userSexLayout);

    }

    //时间选择器
    private void DateSelector() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        //正确设置方式 原因：注意事项有说明
        startDate.set(2020, 1, 1);
        endDate.set(2100, 12, 31);
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                userDateEdit.setText(getTime(date));
            }
        })
                .setContentTextSize(20)
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .build();
        pvTime.show();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    private void saveData() {
        String uName, uSex, uDate, uAge, uHeight, uWeight;
        uName = userNameEdit.getText().toString();
        uSex = userSexEdit.getText().toString();
        uAge = userAgeEdit.getText().toString();
        uHeight = userHeightEdit.getText().toString();
        uDate = userDateEdit.getText().toString();
        uWeight = userWeightEdit.getText().toString();

        if (NumberUtil.checkStringIsNull(uName, uSex, uDate, uAge + "", uHeight + "", uWeight + "")) {
            UserMessage userMessage = new UserMessage();
            userMessage.setMyId("普康");
            userMessage.setUserName(uName);
            userMessage.setUserSex(uSex);
            userMessage.setUserAge(uAge);
            userMessage.setUserHeight(uHeight);
            userMessage.setInDate(uDate);
            userMessage.setUserWeight(uWeight);
            List<UserMessage> list = LitePal.findAll(UserMessage.class);
            if (list.size() == 1) {
                userMessage.updateAll("myId = ?", "普康");//修改指定ID的数据
                //area.updateAll("name = ?","福田")
            } else {
                userMessage.save();
            }
            isNull = false;
        } else {
            isNull = true;
            ToastUtils.show(this, "数据不可为空!");
        }

    }
}
